package com.ziven.common.widget.index;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ziven.easygo.util.EasyUtils;
import com.ziven.easygo.util.Obtain;

import java.util.List;

class RecyclerViewScrollHelper extends RecyclerView.OnScrollListener implements IndexCallback {

    private boolean isTouching = false;
    private int lastScrollPosition = RecyclerView.NO_POSITION;
    private final Obtain<List<FastScrollBlock>> fastScrollBlockListObtain;
    private final Obtain<IndexInterface> indexInterfaceObtain;

    public RecyclerViewScrollHelper(@NonNull Obtain<IndexInterface> obtain1,
                                    @NonNull Obtain<List<FastScrollBlock>> obtain2) {
        indexInterfaceObtain = obtain1;
        fastScrollBlockListObtain = obtain2;
    }

    public void setRecyclerView(@NonNull RecyclerView rv) {
        rv.addOnScrollListener(this);
    }

    @Override
    public void onScrolled(@NonNull RecyclerView rv, int dx, int dy) {
        int position = findFirstVisibleItemPosition(rv.getLayoutManager());
        boolean notUpdate = lastScrollPosition == position;
        lastScrollPosition = position;
        if(isTouching || notUpdate) {
            return;
        }
        FastScrollBlock block = EasyUtils.getValue(fastScrollBlockListObtain.obtain(), position);
        if(block != null) {
            indexInterfaceObtain.obtain().updateIndexName(block.index, block.indexName);
        }
    }

    private int findFirstVisibleItemPosition(RecyclerView.LayoutManager lm) {
        return lm instanceof LinearLayoutManager
                ? ((LinearLayoutManager) lm).findFirstVisibleItemPosition()
                : RecyclerView.NO_POSITION;
    }

    @Override
    public void startUpdateIndexName(int top, int bottom) {
        isTouching = true;
    }

    @Override
    public void updateIndexName(int index, @NonNull String name, int x, int y) {

    }

    @Override
    public void endUpdateIndexName() {
        isTouching = false;
    }
}
